import { getIconListApi } from '@/api/system/svgicon/svgicon'
import { IconListData, IconListParam } from '@/api/system/svgicon/SvgIconModel'
import useInstance from '@/hooks/useInstance'
import { StatusCode } from '@/http/request'
import { onMounted, reactive, nextTick, ref } from 'vue'
import useClipboard from 'vue-clipboard3'

export default function useSvgIcon(emit: any, props: any) {
    const { global } = useInstance()

    const { toClipboard } = useClipboard()

    const iconActive = ref('0')

    // 定义列表查询的参数
    const listParam = reactive<IconListParam>({
        name: ''
    })
    // 表格的高度
    const tableHeight = ref(0)
    // 表格数据
    const iconData = reactive({
        data: Array<IconListData>()
    })
    // 获取表格数据
    const getIconList = async () => {
        let res = await getIconListApi(listParam)
        if (res && res.code == StatusCode.Success) {
            console.log('图标列表：', res)
            iconData.data = res.data
        }
    }

    // 搜索
    const searchBtn = () => {
        getIconList()
    }
    // 重置
    const resetBtn = () => {
        listParam.name = ''
        getIconList()
    }
    const chooseIcon = async (id: string, parent: string, iconName: string) => {
        iconActive.value = iconName
        console.log('iconActive=' + iconActive.value)
        try {
            const iconStr = parent + '-' + iconName
            emit('selectIcon', iconStr)
            if (props.operation == 'list') {
                await toClipboard(iconStr)
                // 信息提示
                global.$message({ message: '复制成功!', type: 'success' })
            }
        } catch (e) {
            console.log(e)
        }
    }

    // 首次加载
    onMounted(() => {
        getIconList()
        nextTick(() => {
            tableHeight.value = window.innerHeight - 180
            iconActive.value = props.currentIcon
            setTimeout(() => {
                const gd = document.getElementById(
                    'icon-' + props.parentIcon
                ) as HTMLElement
                if (gd) {
                    console.log('gd=', gd.offsetTop)
                    window.scroll(0, gd.offsetTop)
                }
            }, 500)
        })
    })

    return {
        iconActive,
        listParam,
        resetBtn,
        searchBtn,
        tableHeight,
        iconData,
        getIconList,
        chooseIcon
    }
}
